<?php

namespace Medicina\BackendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Medicina\KernelBundle\Entity\Cargo;
use Medicina\BackendBundle\Form\CargoType;
use Medicina\BackendBundle\Form\CargoSearchType;

/**
 * Cargo controller.
 *
 */
class CargoController extends Controller {

    /**
     * Lists all Cargo entities.
     *
     */
    public function indexAction() {
        $entity = new Cargo();
        $searchForm = $this->createForm(new CargoSearchType(), $entity);
        $Cargos = new \Doctrine\Common\Collections\ArrayCollection();
        $filter = false;
        $session = $this->get('session');
        $session->set('s_isSearch', false);
        $em = $this->getDoctrine()->getEntityManager();
        $paginador = $this->get('ideup.simple_paginator');
        $paginador->setItemsPerPage(10);
        $request = $this->getRequest();
        $searchForm->bindRequest($request);
        if ($request->getMethod() === 'POST') {
            $searchForm->bindRequest($request);
            $session->set('s_isSearch', true);
            $datos = $searchForm->getData();
            $Cargos = $em->getRepository('MedicinaKernelBundle:Cargo')->getCargoByCriterias($datos);
            $filter = true;
        } else {
            $Cargos = $em->getRepository('MedicinaKernelBundle:Cargo')->findAll();
        }
        $entities = $paginador->paginate($Cargos)->getResult();
        return $this->render('BackendBundle:Cargo:index.html.twig', array(
                    'entities' => $entities,
                    'paginador' => $paginador,
                    'searchCargo' => $searchForm->createView(),
                    'delete_form' => $this->createDeleteForm()->createView()
                ));
    }

    /**
     * Finds and displays a Cargo entity.
     *
     */
    public function showAction($id) {
        $paginador = $this->get('ideup.simple_paginator');
        $paginador->setItemsPerPage(10);
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('MedicinaKernelBundle:Cargo')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Cargo entity.');
        }

        $personas = $em->getRepository('MedicinaKernelBundle:Cargo')->personasParaCargo($id);
//        print_r($em->getRepository('MedicinaKernelBundle:Cargo')->personasParaCargo($id));


        $deleteForm = $this->createDeleteForm($id);

        $entities = $paginador->paginate($personas)->getResult();
        return $this->render('BackendBundle:Cargo:show.html.twig', array(
                    'entity' => $entity,
                    'personas' => $personas,
                    'paginador' => $paginador,
                    'rutaPaginador' => 'cargo_show',
                    'idCargo' => $entity->getId(),
                    'delete_form' => $deleteForm->createView(),
                ));
    }

    /**
     * Displays a form to create a new Cargo entity.
     *
     */
    public function newAction() {
        $entity = new Cargo();
        $form = $this->createForm(new CargoType(), $entity);
        return $this->render('BackendBundle:Cargo:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView()
                ));
    }

    /**
     * Creates a new Cargo entity.
     *
     */
    public function createAction() {
        $entity = new Cargo();
        $request = $this->getRequest();
        $form = $this->createForm(new CargoType(), $entity);
        $form->bindRequest($request);
       // if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            try {
                $em->persist($entity);
                $em->flush();
                //  return $this->redirect($this->generateUrl('cargo_show', array('id' => $entity->getId())));
                return $this->redirect($this->generateUrl('cargo'));


                return $this->render('BackendBundle:Cargo:new.html.twig', array(
                            'entity' => $entity,
                            'form' => $form->createView()
                        ));
            } catch (\PDOException $e) {
                $this->get('session')->setFlash('error', 'Ya existe un cargo con ese codigo, por favor, ingrese uno distinto');
                // return $this->redirect($this->generateUrl('cargo_new'));
                return $this->render('BackendBundle:Cargo:new.html.twig', array(
                            'entity' => $entity,
                            'form' => $form->createView()
                        ));
            }
        //} else {
   //         $this->get('session')->setFlash('error', 'Ya existe un cargo con ese codigo, por favor, ingrese uno distinto');
            // return $this->redirect($this->generateUrl('cargo_new'));}
     //       return $this->render('BackendBundle:Cargo:new.html.twig', array(
      //                  'entity' => $entity,
       //                 'form' => $form->createView()
      //              ));
    //    }
    }

//}

    /**
     * Displays a form to edit an existing Cargo entity.
     *
     */
    public function editAction($id) {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('MedicinaKernelBundle:Cargo')->find($id);

        $editForm = $this->createForm(new CargoType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('BackendBundle:Cargo:edit.html.twig', array(
                    'entity' => $entity,
                    'form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
                ));
    }

    /**
     * Edits an existing Cargo entity.
     *
     */
    public function updateAction($id) {
        $em = $this->getDoctrine()->getEntityManager();
//
//        $entity = $em->getRepository('MedicinaKernelBundle:Cargo')->find($id);
//
//        if (!$entity) {
//            throw $this->createNotFoundException('Unable to find Cargo entity.');
//        }
//
//        $editForm = $this->createForm(new CargoType(), $entity);
//        $deleteForm = $this->createDeleteForm($id);
//
//        $request = $this->getRequest();
//
//        $editForm->bindRequest($request);
//
//        if ($editForm->isValid()) {
//            $em->persist($entity);
//            $em->flush();
//
//            return $this->redirect($this->generateUrl('cargo_edit', array('id' => $id)));
//        }
//
//        return $this->render('BackendBundle:Cargo:edit.html.twig', array(
//                    'entity' => $entity,
//                    'edit_form' => $editForm->createView(),
//                    'delete_form' => $deleteForm->createView(),
//                ));
        $personasOriginales = array();

        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('MedicinaKernelBundle:Cargo')->find($id);

        $this->getOriginales($entity, $personasOriginales);
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Concurso entity.');
        }

        $editForm = $this->createForm(new CargoType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        $request = $this->getRequest();

        $editForm->bindRequest($request);

        //   if ($editForm->isValid()) {
        try {
            $this->removePersonas($entity, $personasOriginales);
            $em->persist($entity);
            $em->flush();
            $this->get('session')->setFlash('notice', 'Cargo guardado correctamente!');

            return $this->redirect($this->generateUrl('cargo', array('id' => $id)));

            //print_r($editForm->getErrors());
            $this->get('session')->setFlash('notice', 'Form successfully executed!');

            return $this->render('BackendBundle:Cargo:index.html.twig', array(
                        'entity' => $entity,
                        'form' => $editForm->createView(),
                        'delete_form' => $deleteForm->createView(),
                    ));
        } catch (\PDOException $e) {
            $this->get('session')->setFlash('error', 'Ya existe un cargo con ese codigo, por favor, ingrese uno distinto');
            // return $this->redirect($this->generateUrl('cargo', array('id' => $id)));
            return $this->render('BackendBundle:Cargo:edit.html.twig', array(
                        'entity' => $entity,
                        'form' => $editForm->createView(),
                        'delete_form' => $deleteForm->createView(),
                    ));
        }
    }

    public function deleteAction($id) {
        $em = $this->getDoctrine()->getEntityManager();
        $entity = $em->getRepository('MedicinaKernelBundle:Cargo')->find($id);

        if (!$entity) {
            $ $this->get('session')->setFlash('error', 'No se encontro el cargo');
        } else {
            try {
                $distinguible = $entity->getTipoDeCargo()->getNombre() . " con codigo " . $entity->getCodigo();
                $em->remove($entity);
                $em->flush();
                $this->get('session')->setFlash('notice', 'Cargo   ' . $distinguible . '  borrado con exito');
            } catch (\PDOException $e) {
                if (!$entity->getConcursos()->isEmpty()) {
                    $this->get('session')->setFlash('error', 'No se puede borrar el cargo ' . $distinguible . ' , esta siendo usado por un concurso');
                } else {
                    if (!$entity->getPersonas()->isEmpty()) {
                        $this->get('session')->setFlash('error', 'No se puede borrar el cargo ' . $distinguible . ' , contiene información acerca de las personas que lo ocuparon');
                    }
                }
            }
        }

        return $this->redirect($this->generateUrl('cargo'));
    }

    private function createDeleteForm() {
        return $this->createFormBuilder()->getForm();
    }

    protected function getOriginales($object, &$personasOriginales) {
        foreach ($object->getPersonas() as $persona)
            $personasOriginales[] = $persona;
    }

    protected function removePersonas($object, &$originalPersonas = array()) {
        $this->removeElements($object->getPersonas(), $originalPersonas);
    }

    protected function removeElements($elements, &$original = array()) {
        foreach ($elements as $el) {
            foreach ($original as $key => $toDel) {
                if ($toDel->getId() === $el->getId()) {
                    unset($original[$key]);
                }
            }
        }
        // Elimina la relaciÃ³n entre el concurso  y la PersonaInscripta
        foreach ($original as $el) {
            $em = $this->getDoctrine()->getEntityManager();
            $em->remove($el);
        }
    }

    public function getByCatedraAction($catedraId) {
        $entity = new Cargo();
        $searchForm = $this->createForm(new CargoSearchType());
        $Cargos = new \Doctrine\Common\Collections\ArrayCollection();
        $filter = false;
        $session = $this->get('session');
        $session->set('s_isSearch', false);
        $em = $this->getDoctrine()->getEntityManager();
        $paginador = $this->get('ideup.simple_paginator');
        $paginador->setItemsPerPage(10);
        $request = $this->getRequest();
        $searchForm->bindRequest($request);
        $Cargos = $em->getRepository('MedicinaKernelBundle:Cargo')->cargosParaCatedra($catedraId);
        $catedra = $em->getRepository('MedicinaKernelBundle:Catedra')->find($catedraId);
        $entities = $paginador->paginate($Cargos)->getResult();
        return $this->render('BackendBundle:Cargo:index.html.twig', array(
                    'entities' => $entities,
                    'paginador' => $paginador,
                    'searchCargo' => $searchForm->createView(),
                    'title' => "Listado de cargos asociados a catedra " . $catedra->getNombre(),
                    'delete_form' => $this->createDeleteForm()->createView()
                ));
    }

}
